package com.leefine.nettysocketproxy.support;

import com.leefine.nettysocketproxy.proxy.SocketProxyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ThreadHelper
 *
 * @Author lihuai.chen@163.com
 * @Date 6/10/2021 10:58 AM
 */
public class ThreadHelper {
    private final static Logger logger = LoggerFactory.getLogger(ThreadHelper.class);
    private final static String THREAD_PREX = "SocketProxyServer:";

    public static String getThreadStateByName(String name) {
        name = THREAD_PREX + name;
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);

        for (int i = 0; i < noThreads; i++) {
            String nm = lstThreads[i].getName();
            if (nm.equals(name)) {
                return lstThreads[i].getState().name();
            }
        }

        return "Stoped";
    }

    public static boolean killThreadByName(String name) {
        name = THREAD_PREX + name;
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);

        for (int i = 0; i < noThreads; i++) {
            String nm = lstThreads[i].getName();
            if (nm.equals(name)) {
                lstThreads[i].interrupt();
                logger.info("Thread killed:" + nm);
                return true;
            }
        }

        return false;
    }

    public static boolean startThread(SocketProxyServer socketProxyServer) {
        try {
            Thread thread = new Thread(() -> {socketProxyServer.run(); });
            thread.setName(THREAD_PREX + socketProxyServer.getName());
            thread.start();
            logger.info("Thread start:" + socketProxyServer.getName());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}